const router = require('koa-router')()
const verify = require('../service/verify-password')
const {getAuthorByAccount} = require('../dao/get-author')
const getImage = require('../dao/get-image')

router.prefix('/login')

router.get('/', async (ctx, next) => {
    await ctx.render('login')
})

router.post('/', async (ctx, next) => {
    let postDate = ctx.request.body,
        account = postDate.account,
        password = postDate.password,
        result = await verify(account, password)
    if (result) {
        ctx.session.currentUser = account  // 保存session
        ctx.body = {'success': true}
    } else {
        ctx.body = {'success': false}
    }
})
router.post('/status', async (ctx, next) => {
    let user = ctx.session.currentUser
    if (user) {
        let info = {
            statusCode: 1
        }
        ctx.body = JSON.stringify(info)
    } else {
        let info = {
            statusCode: 0
        }
        ctx.body = JSON.stringify(info)
    }
})

router.post('/userInfo', async (ctx, next) => {
    let user = ctx.session.currentUser
    if (user) {
        let author = await getAuthorByAccount(user),
            imageId = author.portrait_id,
            image = await getImage(imageId),
            username = author.username,
            userId = author.id,
            imageUrl = image.thumb_path
        info = {
            statusMag: {username, userId, imageUrl},
            statusCode: 1
        }
        ctx.body = JSON.stringify(info)
    } else {
        let info = {
            statusCode: 0
        }
        ctx.body = JSON.stringify(info)
    }
})

router.post('/out', async (ctx, next) => {
    ctx.session.currentUser = null
    let info = {
        statusCode: Boolean
    }
    try {
        info.statusCode = 1
        ctx.body = JSON.stringify(info)
    } catch (err) {
        info.statusCode = 0
        ctx.body = JSON.stringify(info)
    }
})

module.exports = router